package com.example.alarmdemo;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.util.Locale;

/**
 * @创建时间：2019/10/21 10:16
 * @描述：
 */
public class TextToSpeechUtil {
    private static TextToSpeechUtil mTextToSpeechUtil;
    private static TextToSpeech mTextToSpeech;
    private static Context mContext;
    private static float pitch = 0.5f;
    private static float speechRate = 1f;
    private static String speak = null;
    private static TextToSpeech.OnInitListener mOnInitListener = new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                int result = mTextToSpeech.setLanguage(Locale.CHINA);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(mContext, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
                } else {
                    mTextToSpeech.setPitch(pitch);// 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
                    mTextToSpeech.setSpeechRate(speechRate);   //设定语速 ，默认1.0正常语速
                    mTextToSpeech.speak(speak,TextToSpeech.QUEUE_FLUSH,null);
                }
            }
        }
    };

    private TextToSpeechUtil() {
        init(mContext);
    }

    private void init(Context context) {
        if (mTextToSpeech == null) {
            mTextToSpeech = new TextToSpeech(context.getApplicationContext(), mOnInitListener);
        }
    }


    public static synchronized TextToSpeechUtil getInstance(Context context) {
        if (mTextToSpeechUtil == null) {
            mContext = context;
            mTextToSpeechUtil = new TextToSpeechUtil();
        }
        return mTextToSpeechUtil;
    }

    public void setPitch(float pitch) {
        this.pitch = pitch;
    }
    public void addSpeak(String speak){
        mTextToSpeech.speak(speak,TextToSpeech.QUEUE_ADD,null);
    }
    public void setSpeechRate(float speechRate) {
        this.speechRate = speechRate;
    }

    public void speak(String s) {
        if (TextUtils.isEmpty(this.speak)){
            this.speak=s;
            mTextToSpeech.speak(s,TextToSpeech.QUEUE_FLUSH,null);
        }else {
            mTextToSpeech.speak(s,TextToSpeech.QUEUE_ADD,null);
        }

    }

    public void stop() {
        mTextToSpeech.stop();
    }

    public void finish() {
        mTextToSpeech.shutdown();
    }

    public boolean isSpeaking() {
        return mTextToSpeech.isSpeaking();
    }
}
